package com.lmy.androidcustomview.touch

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.util.SparseArray
import android.view.MotionEvent
import android.view.View
import com.lmy.androidcustomview.R
import com.lmy.androidcustomview.dp

/**
 * @author
 * @功能:多点绘制 画板功能
 * 互不相关形
 * @Creat 2/14/21 1:44 PM
 * @Compony 465008238@qq.com
 */
class MultiTouchView5(context: Context, attrs: AttributeSet) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.parseColor("#eb5373")
        style = Paint.Style.STROKE
        strokeWidth = 4.dp
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND

    }
    private val pathsMap = mutableMapOf<Int, Path>()

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        pathsMap.forEach {
            canvas.drawPath(it.value, paint)
        }
    }
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
                var path = Path()
                //移动到当前手指点击的位置 包括第一根手指和第二根手指依次类推
                val actionIndex = event.actionIndex
                path.moveTo(event.getX(actionIndex), event.getY(actionIndex))
                /**
                 * 注意这里不能使用Index来作为Map的Key 因为Inde是不稳定的可变的
                 */
                pathsMap[event.getPointerId(actionIndex)] = path
                invalidate()
            }
            MotionEvent.ACTION_MOVE -> {
                /**
                 *我们根据Map中存的PointerId来算出对应的手指index 然后在Move事件中取出这根手指的实时坐标并更新到Path中
                 */
                for ((key, value) in pathsMap) {
                    value.lineTo(
                        event.getX(event.findPointerIndex(key)),
                        event.getY(event.findPointerIndex(key))
                    )
                }
                invalidate()
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
                /**
                 * 不管是哪一个手指抬起
                 * 只要获取当前的抬起的actionIndex然后 获取pointerId
                 * 根据pointerId来移除Map中的数据 重新绘制界面即可
                 */
                var actionIndex = event.actionIndex
                val pointerId = event.getPointerId(actionIndex)
                pathsMap.remove(pointerId)
                invalidate()
            }
        }
        return true
    }
}

